package com.hsmpay.common.util.jiami;

import com.hsmpay.common.util.JSONStringBuilder;
import it.sauronsoftware.base64.Base64;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Security;
import java.util.LinkedHashMap;
import java.util.Map;

//import zyzf.utils.TimeUtils;

public class JiamiTest {
    public static String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKyRht3mRFhkBNFC" + "\r" +
            "AS5x3VVVmHoZbJP73l/K40bmRmbgDIu8lp5R3aPbahYfVoo+PUpWUKxmPD7SzDnh" + "\r" +
            "8g3xlYS4hufWh5IpnNhHxoIqoJWIZuf0U6k7ao99mbZPZSdXmjpmrnjvWXYu42LA" + "\r" +
            "0tMOpu7DxSaeOPrqj9JgQ5a5cFZrAgMBAAECgYEApvJa0U21jPWmG3OJhQ8vGyEl" + "\r" +
            "0+nIuxmNtoqnea3JKjlSqdUWua9lhuH8Lc6/gBpaXRJIFaEKY5S3cr/91jODez3q" + "\r" +
            "Grngl/D/AMsx/NAaj30XzUAf3OObKWVTZdNERUUuxafeLM8xNbhUhS0F8AMdc8z3" + "\r" +
            "O/u+w3HTTJ8gqdtpWuECQQDW2MMV9c/oH6GsDk9l9UCOmoNHFmQkPLV90/ws35Oj" + "\r" +
            "tsqpYv4KP4ZbUaw7pkJkCPHzHfYAI0xw1C67GQUrGKtZAkEAzZ+a66FkxJcext0Q" + "\r" +
            "Dz+lu1JMkE79zXVET310h6JY/xAKuqOCAw+pQcQQv8XuEi3OxnMZcfD1KFh0Zuxu" + "\r" +
            "mutLYwJBANFtgt2JPB09mE8rs+HjbAaWP5mwDfX058W8OnlTh4tyx6LOSGyc989U" + "\r" +
            "kdujedwhjBg9AGup/P2PF+5xuUQFTCECQBwb6HKzsnHJctSenbZn7gEIhBzqH3n5" + "\r" +
            "wOfY75gnEmFz0POorHo8ptettNhyd1QW3QB19ZGE7g6g4PC8+3XEGp8CQDHOTLDo" + "\r" +
            "UxB7dO3W5q2DFFjbbWNB/Fw2DRMbh6xYLrLNXoXRUByjCbKtDLuRF2PnUlMIEaV/" + "\r" +
            "EB011IK3iTQMLYc=" + "\r";

	public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCskYbd5kRYZATRQgEucd1VVZh6" + "\r" +
            "GWyT+95fyuNG5kZm4AyLvJaeUd2j22oWH1aKPj1KVlCsZjw+0sw54fIN8ZWEuIbn" + "\r" +
            "1oeSKZzYR8aCKqCViGbn9FOpO2qPfZm2T2UnV5o6Zq5471l2LuNiwNLTDqbuw8Um" + "\r" +
            "njj66o/SYEOWuXBWawIDAQAB" + "\r";
    private static Logger log = Logger.getLogger(JiamiTest.class);

    static {//安全性
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    //测试接口 是否可以用
    public static void main(String args[]) {
        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();
            result.put("clientType", 3);
            result.put("terminalTypeId", 1);
            result.put("roleId", 2);
            result.put("action", "checkFunction_getVisibleFunction");
            //1--------------------测试获取银行列表
            //diaoyong("{\"action\":\"bankAction_searchBankList\",\"clientType\":2,\"terminalTypeId\":1,\"roleId\":2}");
            /*result.put("action", "bankAction_searchBankList");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //2--------------------测试注册下一步按钮
            //diaoyong("{\"action\":\"userAction_firstNextBnRegister\",\"clientType\":2,\"terminalTypeId\":1,\"roleId\":2,\"mobile\":\"13521856049\",\"activationCode\":\"ABCD\"}");
			/*result.put("action", "userAction_firstNextBnRegister");
			result.put("mobile", "13521856049");
			result.put("activationCode", "ABCD");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //3--------------------1.1.3、用户注册
			/*result.put("action", "userAction_register");
			result.put("mobile", "13521856049");
			result.put("activationCode", "fff4");
			result.put("password", "123456");
			result.put("bankCard", "6222600910060241963");
			result.put("openingBank", "交通银行");
			result.put("userName", "颜铃璋");
			result.put("branchesBankId", 56793);
			result.put("businessRangeId", 1);
			result.put("businessAddress", "北京市西城区广安门外大街168号朗琴国际B座607");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //4--------------------1.1.4、登录
			/*result.put("action", "userAction_login");
			result.put("uniqueId", "手机唯一标识");
			result.put("loginType", 1);
			result.put("mobile", "13521856049");
			result.put("password", "123456");
			result.put("bankCard","6222600910060241963");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/


            //5--------------------1.1.5、查询用户名（刷卡登录  步骤1）
			/*result.put("action", "userAction_searchMobileByBankCard");
			result.put("bankCard","6222600910060241963");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //6--------------------1.1.8、注销用户
			/*result.put("action", "userAction_userLogout");
			result.put("userId",3544);
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //7--------------------1.1.9、修改密码
			/*result.put("action", "userAction_updateUserPasseword");
			result.put("userId",3664);
			result.put("oldPassword",123456);
			result.put("password",123456);
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //---------------------1.1.10、账户金钱信息
			/*result.put("action", "userMoneyAction_searchUserMoney");
			result.put("userId",1);
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //---------------------1.1.12、查询支行
			/*result.put("action", "userDPIAction_userDPI");
			result.put("bankId",12);
			result.put("bBankProvince",1);
			result.put("bBankCity",1000);
			diaoyong(JSONStringBuilder.getAjaxString(result));*/
			
			/*String img[] = {"F:\\ylz.jpg","F:\\ylz.jpg"};
			upload(img,"http://10.0.0.66:8080/proOneMobile/forward/fc.action");*/

            //---------------------1.1.12、查询支行
			/*result.put("action", "bankAction_searchBranchesBankList");
			result.put("bankId",12);
			result.put("bBankProvince",1);
			result.put("bBankCity",1000);
			result.put("bBankName","北京");
			result.put("start",1);
			result.put("stop",20);
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //----------------------------查询余额
			/*result.put("action", "balance_balanceEnquiry");
			result.put("userId", "444");
			result.put("functionKey", "functionKey");
			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
			result.put("terminalId", "1050000000009A41D607");
			result.put("accountNumber", "6210300016512078");
			result.put("pin", "147258");
			result.put("track2Data", "6210300016512078d49121206307260000000");
			result.put("track3Data", "");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //--------------------------收款
//			result.put("action", "purchase_receivablesToCard");
//			result.put("userId", "444");
//			result.put("functionKey", "functionKey");
//			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
//			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
//			result.put("terminalId", "1050000000009A41D607");
//			result.put("transAmt", "1");
//			result.put("accountNumber", "6210300016512078");
//			result.put("pin", "147258");
//			result.put("track2Data", "6210300016512078d49121206307260000000");
//			result.put("track3Data", "");
//			diaoyong(JSONStringBuilder.getAjaxString(result));

            //--------------------------1.5.2、撤销（实时收款）
			/*result.put("action", "revocation_revocation");
			result.put("userId", "13");
			result.put("functionKey", "functionKey");
			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
			result.put("orgMerchantOrderId", "20140721173825862612");
			result.put("terminalId", "1050000000009BE30308");
			result.put("transAmt", "10000");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //----------------------------1.3.4、信用卡还款
			/*result.put("action", "creditRepayment_creditRepayment");
			result.put("userId", "503");
			result.put("functionKey", "functionKey");
			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
			result.put("terminalId", "1050000000009A41D607");
			result.put("transAmt", "1");
			result.put("accountNumber", "6210300016512078");
			result.put("pin", "147258");
			result.put("track2Data", "6210300016512078d49121206307260000000");
			result.put("track3Data", "");
			result.put("creditNumber", "6259960005135454");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //------------------------------卡卡转账
			/*result.put("action", "transfer_transfer");
			result.put("userId", "503");
			result.put("functionKey", "functionKey");
			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
			result.put("terminalId", "1050000000009A41D607");
			result.put("transAmt", "300");
			result.put("accountNumber", "6210300016512078");
			result.put("pin", "147259");
			result.put("track2Data", "6210300016512078d49121206307260000000");
			result.put("track3Data", "");
			result.put("accountNumber2", "6212260200044981823");//转入卡卡号
			result.put("accountName", "包月飞");//转入账户名
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //-----------------------------1.3.7、查询订单
			/*result.put("action", "enquiry_enquiry");
			result.put("userId", "13");
			result.put("merchantOrderId", "20140509042620081748680");
			result.put("terminalId", "1050000000009BE30308");
			diaoyong(JSONStringBuilder.getAjaxString(result));*/

            //-----------------------------1.3.8、
			/*result.put("action", "callsRecharge_recharge");
			result.put("userId", "503");
			result.put("functionKey", "functionKey");
			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
			result.put("terminalId", "1050000000009A41D607");
			result.put("transAmt", "5000");
			result.put("accountNumber", "6210300016512078");
			result.put("pin", "147259");
			result.put("track2Data", "6210300016512078d49121206307260000000");
			result.put("track3Data", "");
			result.put("accountNumber2", "6212260200044981823");//转入卡卡号
			result.put("phoneNum", "13521856049");//转入卡卡号
			diaoyong(JSONStringBuilder.getAjaxString(result));*/


            //-----------------------------版本
//			result.put("action", "terminalVersionAction_checkVersion");
//			result.put("version", "1.0.0.3.8");
//			diaoyong(JSONStringBuilder.getAjaxString(result));

            //-----------------------------版本
//			result.put("action", "userAction_updateCrashT1Type");
//			result.put("version", "1.0.0.3.8");
//			diaoyong(JSONStringBuilder.getAjaxString(result));

            //-----------------------------提现
			/*result.put("action", "cashMoney_cashMoney");
			result.put("userId", "444");
			result.put("money", "10000");
			result.put("functionKey", "CASHMONEY");
			diaoyong(JSONStringBuilder.getAjaxString(result));;*/
			
			/*result.put("action", "cashMoneySafe_uploadCardCerd");
			diaoyong(JSONStringBuilder.getAjaxString(result));;*/


//			result.put("action", "violation_getRuleProvince");
//			result.put("userId", "13");
//			result.put("item", "00");
//			result.put("functionKey", "functionKey");
//			diaoyong(JSONStringBuilder.getAjaxString(result));

//			result.put("action", "wiolation_getProvince");
//			result.put("userId", "13");
//			result.put("item", "00");
//			result.put("functionKey", "functionKey");

//			result.put("action", "userAction_bindingBankCard");
//			result.put("userId", "444");
//			result.put("bankCard", "6226220112722482");
//			result.put("userName", "颜铃璋");
//			result.put("openingBank", "中国民生银行");
//			result.put("bBankProvince", 1);
//			result.put("bBankCity", 1000);
//			result.put("branchesBankId", 61813);

            //1.8.4、查询 快捷支付银行列表
//			result.put("action", "shortcutPurchaseNL_searchFastBankList");
//			result.put("userId", "438");
//			result.put("cardType", "credit");

            //1.8.1、下单及发送短信
//			result.put("action", "shortcutPurchaseNL_fastSms");
//			result.put("userId", "438");
//			result.put("merchantOrderTime", TimeUtils.getNowDateTime("yyyyMMddHHmmss"));
//			result.put("merchantOrderId", TimeUtils.getNowDateTime("yyyyMMddHHmmssSSS"));
//			result.put("subject", "测试商品");
//			result.put("body", "商品描述");
//			result.put("transAmt", "1");
//			result.put("cardType", "debit");
//			result.put("bankCode", "CMBC");
//			result.put("accountNumber", "6226220112722482");
//			result.put("purchaseName", "颜铃璋");
//			result.put("idCard", "430923198911167515");
//			result.put("mobile", "13521856049");
//			result.put("expireMonth", "");
//			result.put("expireYear", "");
//			result.put("cvv", "");
//			result.put("agreeNo", "");

            //查询支行
//			result.put("action", "bankAction_searchBranchesBankList");
//			result.put("roleId", "2");
//			result.put("bankId", 34);
//			result.put("bBankProvince", 1);
//			result.put("bBankCity", 1000);
//			result.put("bBankName", "地安门");
//			result.put("start", 1);
//			result.put("stop", 20);

            //绑定银行卡
//			result.put("action", "userAction_updateBindingBankCard");
//			result.put("userId", 438);
//			result.put("bankCard", "6222600910060241963");
//			result.put("oldBankCard", "6226220112722482");
//			result.put("openingBank", "民生银行");
//			result.put("bBankProvince", "1");
//			result.put("bBankCity", "1000");
//			result.put("branchesBankId", 72779);

            diaoyong(JSONStringBuilder.getAjaxString(result));

            String str = "==================8C23022DD39F2AC3B4A2377813CF9AAE";
            log.debug("=====================" + str.substring(str.length() - 32));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String diaoyong(String json) throws Exception {
        String terminalTypeId = new String(Base64.encode("1".getBytes("UTF-8")), "UTF-8");
        RSAObjectC rsaEncrypt = RSAObjectC.getInstance(publicKey, privateKey);
        byte[] desKeyB = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), "8C23022DD39F2AC3B4A2377813CF9AAE".getBytes("Utf-8"));
        //byte[] desKeyB = RSAUtils.encryptByPublicKey("8C23022DD39F2AC3B4A2377813CF9AAE".getBytes("Utf-8"), publicKey);
        String desKey = new String(Base64.encode(desKeyB), "UTF-8");
        log.debug("#" + desKey + "#");
        log.debug("#################json#" + json + "#");
		/*byte[] dataB = DesUtil.encrypt(json.getBytes("Utf-8"), "8C23022DD39F2AC3B4A2377813CF9AAE".getBytes("Utf-8"));
		String data = new String(Base64.encode(dataB),"UTF-8");*/
        String data = Des3.encode(json, "8C23022DD39F2AC3B4A2377813CF9AAE");

        log.debug("#" + data + "#");
        String str = terminalTypeId + "|" + desKey + "|" + data;//"1|"+desKey+"|"+data;
        log.debug("参数：" + str);
        //str = Base64.encode(str);

        return httpClientUtils(str);
    }

    private static String sessionId = "JSESSIONID=983A81651D1CCFE7122462A1B2FE87F1";

    public static String httpClientUtils(String XML) throws Exception {
        String Method = "POST";
        String xmlString = XML;
        byte[] xmlData = xmlString.getBytes();
        try {
            xmlData = xmlString.getBytes("UTF-8");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        String urlStr = "http://localhost:8080/proOneMobile/forward/fc.action";
        //String urlStr = "http://42.62.5.102:8080/proOneMobile/forward/fc.action";
//		String urlStr = "http://42.62.5.100:8000/proOneMobile/forward/fc.action";
        //String urlStr = "http://211.157.145.16:8080/zfPayMobile/forward/fc.action";//生产环境  上生产密钥得换
        BufferedReader rd = null;
        String msg = "";
        log.warn("请求URL:" + urlStr);
        log.warn("请求参数:" + XML);
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestMethod(Method);
            urlCon.setConnectTimeout(120000);
            urlCon.setReadTimeout(120000);
            //System.setProperty("sun.net.client.defaultConnectTimeout", "120000");
            //System.setProperty("sun.net.client.defaultReadTimeout", "120000");
            urlCon.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            urlCon.setRequestMethod("POST");
//			if(null != sessionId)
            urlCon.setRequestProperty("Cookie", "SESSION_COOKIE=s103;JSESSIONID=983A81651D1CCFE7122462A1B2FE87F1");
            //urlCon.setRequestProperty("Cookie", "JSESSIONID=BBEBB4F78F7490EC657B6EA74989DE9C");
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            log.warn("数据发送完成,等待响应...");
            rd = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "utf-8"));
            String inputLine;
            while ((inputLine = rd.readLine()) != null)
                msg += inputLine;
            log.warn("解密前数据:" + msg);
            //解密
            String[] strArray = msg.split("\\|");
            if (strArray.length == 3) {
                if ("1".equals(strArray[0])) {//成功信息
					/*byte[] dataB = Base64.decode(strArray[1].getBytes("UTF-8"));
					String data = new String(DesUtil.decrypt(dataB, "8C23022DD39F2AC3B4A2377813CF9AAE".getBytes("UTF-8")),"UTF-8");*/
                    String data = Des3.decode(strArray[1], "8C23022DD39F2AC3B4A2377813CF9AAE");
                    strArray[1] = data;
                    log.warn("响应数据为:" + data);
                } else {
                    String code = strArray[1];
                    log.warn("错误代码:" + code);
                    String eMsg = new String(Base64.decode(strArray[2].getBytes("UTF-8")), "UTF-8");
                    log.warn("错误描述:" + eMsg);
                }
            }

            String cookieValue = urlCon.getHeaderField("Set-Cookie");
            log.debug("cookie value:" + cookieValue);
            sessionId = cookieValue.substring(0, cookieValue.indexOf(";"));
            log.debug("sessionId:" + sessionId);
            //log.warn("响应数据为:"+msg);
            rd.close();
        } catch (Exception e) {
            //e.printStackTrace();
            throw e;
        }
        return msg;
    }

    @SuppressWarnings("unused")
    private static void upload(String[] uploadFiles, String actionUrl) {
        String end = "/r/n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            URL url = new URL(actionUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            DataOutputStream ds =
                    new DataOutputStream(con.getOutputStream());

            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " +
                    "name=\"action\"" + end);
            ds.writeBytes(end);
            ds.writeBytes("");
            for (int i = 0; i < uploadFiles.length; i++) {
                String uploadFile = uploadFiles[i];
                String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
                ds.writeBytes(twoHyphens + boundary + end);
                ds.writeBytes("Content-Disposition: form-data; " +
                        "name=\"file" + i + "\";filename=\"" +
                        filename + "\"" + end);
                ds.writeBytes(end);
                FileInputStream fStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                while ((length = fStream.read(buffer)) != -1) {
                    ds.write(buffer, 0, length);
                }
                ds.writeBytes(end);
                /* close streams */
                fStream.close();
            }
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            ds.flush();
            // 定义BufferedReader输入流来读取URL的响应  
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            String s = b.toString();
            if (s.contains("successfully")) {
                // for (int i = 1; i < 5; i++) {
                int beginIndex = s.indexOf("url =") + 5;
                int endIndex = s.indexOf("/n", beginIndex);
                String urlStr = s.substring(beginIndex, endIndex).trim();
                log.debug(urlStr);
                // }
            }
            ds.close();
        } catch (Exception e) {
        }
    }

}
